/**
 * Created with  SublimeText
 * @Author:      Bert
 * @DateTime:    2016-12-26 10:19:40
 * @Description: 
 */

define(function(require, exports, module) {

    var tpl = require('{base}/tpls/myProfileActivities.tpl'),
        tplL = require('{base}/tpls/myProfileActivitiesL.tpl'),
        condition = {},
        userObj;

    var component = {

        template: _.template(tpl),
        templateL: _.template(tplL),

        defaultData: function() {
            condition = {
                page_num: 0,
                offset: 20,
                from: 0,
                prof_id: this.getTplData().userInfo.account.usr_id
            };
        },


        render: function(page, obj) {
            this.page = page;
            this.defaultData();
            userObj = this.getTplData().userInfo;
            return this.template(this.getTplData());
        },

        componentMount: function() {
            this.bindEvt();
            this.myProfileActivitiesRender();
        },

        componentUpdate: function() {

        },

        bindEvt: function() {

            var tthis = this,
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileActivities\']');
            Dom.on('click', '.activitiesComment', function() {
                tthis.addCommentForm($(this).closest('dd'));
            });
            Dom.on('click', '.cancel', function() {
                $(this).closest('.editBox').remove();
            });
            Dom.on('click', '.activitiesLike', function() {
                tthis.ajaxLike($(this).closest('dd').attr('activityid'), $(this));
            });
            Dom.on('input', '.editBox textarea', function() {
                var btnSave = $(this).closest('.editBox').find('.btnSave');
                if ($.trim($(this).val()).length > 0) {
                    btnSave.removeClass('btnDisabled');
                } else {
                    btnSave.addClass('btnDisabled');
                }
            });
            Dom.on('click', '.editBox .btnSave', function() {
                if ($(this).hasClass('btnDisabled')) {
                    return;
                };
                var obj = {
                    'activity_id': $(this).closest('dd').attr('activityid'),
                    'text': $.trim($(this).closest('.editBox').find('textarea').val()),
                    'activity_type': 2
                };
                if (obj.text.length > 0) {
                    tthis.ajaxComment(obj, $(this).closest('dd'));
                };
            });
            Dom.on('click', '.activitiesMore', function() {
                tthis.ajaxListActivities(condition);
            });
            Dom.on('click', '.activitiesHideNote span', function() {
                tthis.setActivityPrivacy($(this).attr('val'), $(this).closest('.activitiesHideNote'));
            });

        },

        getTplData: function() {
            var obj = {
                userInfo: JSON.parse(Util.getSessionStorage('userInfo')),
                userStatus: JSON.parse(Util.getSessionStorage('userStatus'))
            }
            return obj;
        },

        myProfileActivitiesRender: function() {
            var tthis = this,
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileActivities\']'),
                privacyDom = Dom.find('.activitiesHideNote');
            if (Dom.find('.activitiesList').find('dd').length == 0 && parseInt(userObj.privacy_setting.activity_hide) == 0) {
                tthis.ajaxListActivities(condition)
            };
            if (parseInt(userObj.privacy_setting.activity_hide) == 0) {
                privacyDom.html(Lang.myProfileActivitiesHideNote + ' <span val="hide_activity">' + Lang.myProfileActivitiesHideBtn + '</span>.');
            } else {
                privacyDom.html(Lang.myProfileActivitiesUnHideNote + ' <span val="unhide_activity">' + Lang.myProfileActivitiesUnHideBtn + '</span>.');
            }
        },

        ajaxListActivities: function(data) {
            var tthis = this,
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileActivities\']'),
                contentDom = Dom.find('.activitiesList'),
                morBtn = contentDom.find('.activitiesMore');
            var ajaxObj = {
                url: seajs.data.vars.apiUrl + 'activity',
                type: 'POST',
                data: data,
                success: function(data) {
                    if (data.res.length < 1 && contentDom.find('dd').length < 1) {
                        tthis.noData(contentDom);
                        return;
                    } else if (data.res.length > 0) {
                        contentDom.append(tthis.templateL({ arr: data.res }));
                        condition['page_num']++;
                        if (parseInt(data.res.length) > (parseInt(condition.offset) - 1)) {
                            contentDom.append('<div class="activitiesMore">See more activities</div>');
                        };
                    }
                },
                error: function(xhr, errorType, error) {},
                complete: function(xhr, status) {
                    Share.ajaxEndB(contentDom);
                }
            };
            morBtn.remove();
            Share.ajaxStartB(contentDom);
            $.ajax(Share.ajaxControl(ajaxObj));
        },

        ajaxLike: function(activityId, likeBtn) {
            var tthis = this;
            var ajaxObj = {
                url: seajs.data.vars.apiUrl + 'activity_like',
                type: 'POST',
                data: { activity_id: activityId },
                success: function(data) {
                    var praiseDom = likeBtn.closest('dd').find('.activitiesPraise');
                    if (!likeBtn.hasClass('activitiesLiked')) {
                        likeBtn.addClass('activitiesLiked');
                        var addHtml = '<a userId="' + userObj.account.usr_id + '"><img width="30" height="30" src="' + userObj.photo.icon + '" /></a>';
                        if (praiseDom.length > 0) {
                            praiseDom.append(addHtml);
                        } else {
                            likeBtn.closest('dd').find('.activitiesOperation').after('<div class="activitiesPraise"><span><b></b></span>' + addHtml + '</div>');
                        }
                    } else {
                        likeBtn.removeClass('activitiesLiked');
                        var delDom = praiseDom.find('a[userId=\'' + userObj.account.usr_id + '\']');
                        if (delDom.length > 0) {
                            delDom.remove();
                            if (praiseDom.find('a').length == 0) {
                                praiseDom.remove();
                            }
                        }
                    }
                },
                error: function(xhr, errorType, error) {},
                complete: function(xhr, status) {
                    Share.pageLoad(false);
                }
            };
            Share.pageLoad(true);
            $.ajax(Share.ajaxControl(ajaxObj));
        },

        ajaxComment: function(data, infoDom) {
            var tthis = this;
            var ajaxObj = {
                url: seajs.data.vars.apiUrl + 'add_activity_comment',
                type: 'POST',
                data: data,
                success: function(data) {
                    if (data.res) {
                        var commentDom = infoDom.find('.activitiesCommentList');
                        var addHtml = '<li><div class="activitiesCommentAvatar" userId="' + data.res.author_id + '"><img height="30" width="30"  src="' + data.res.icon + '" /></div> <h5><div>' + data.res.username + '</div><span>Posted on ' + data.res.sent_date + '</span></h5><div class="activitiesCommentContent">' + data.res.text + '</div></li>';
                        if (commentDom.length == 0) {
                            var afterDom = infoDom.find('.activitiesOperation');
                            if (infoDom.find('.activitiesPraise').length > 0) {
                                afterDom = infoDom.find('.activitiesPraise');
                            };
                            afterDom.after('<ul class="activitiesCommentList">' + addHtml + '</ul>');
                        } else {
                            commentDom.append(addHtml);
                        };
                    }
                },
                error: function(xhr, errorType, error) {},
                complete: function(xhr, status) {
                    Share.pageLoad(false);
                }
            };
            Share.pageLoad(true);
            $.ajax(Share.ajaxControl(ajaxObj));
        },

        addCommentForm: function(addDom) {
            if (addDom.find('.editBox').length == 0) {
                var addHtml = '<div class="editBox editBoxActive"><textarea placeholder="Add a comment..." maxlength="250"></textarea><div class="submitBox"><div class="btnCancel cancel">cancel</div><div class="btn btnDisabled btnSave save">comment</div></div></div>';
                addDom.append(addHtml);
            }

        },

        setActivityPrivacy: function(val, privacyDom) {
            var tthis = this,
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileActivities\']');
            var ajaxObj = {
                url: seajs.data.vars.apiUrl + 'set_activity_privacy',
                type: 'POST',
                data: { 'action': val },
                success: function(data) {
                    if (parseInt(data.results) == 1) {
                        var userInfo = JSON.parse(Util.getSessionStorage('userInfo'));
                        if ($.trim(val) == 'hide_activity') {
                            userInfo.privacy_setting.activity_hide = '1';
                            privacyDom.html(Lang.myProfileActivitiesUnHideNote + ' <span val="unhide_activity">' + Lang.myProfileActivitiesUnHideBtn + '</span>.');
                            Dom.find('.activitiesList').html('');
                        } else {
                            userInfo.privacy_setting.activity_hide = '0';
                            privacyDom.html(Lang.myProfileActivitiesHideNote + ' <span val="hide_activity">' + Lang.myProfileActivitiesHideBtn + '</span>.');
                            condition.page_num = 0;
                            tthis.ajaxListActivities(condition);
                        };
                        Util.setSessionStorage('userInfo', JSON.stringify(userInfo));
                    }

                },
                error: function(xhr, errorType, error) {},
                complete: function(xhr, status) {
                    Share.pageLoad(false);
                }
            };
            Share.pageLoad(true);
            $.ajax(Share.ajaxControl(ajaxObj));
        },

        noData: function(dom) {
            dom.append('<div>no data</div>');
        },

        affectOtherChange: function(typeString) {
            if (this.page.myProfileActivitiesComponentChange) {
                this.page.myProfileActivitiesComponentChange(typeString);
            }
        },
    }

    module.exports = component;
});
